package org.geekbang.projects.cs.im.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.geekbang.projects.cs.im.handler.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description:
 * @author: Kaijun Chen
 * @date: 2023/3/15
 **/
public class ClientTest {

    private static Logger logger = LoggerFactory.getLogger(ClientTest.class);

    public static String userid = "100001";
    public static String userName = "陈";
    public static String host = "127.0.0.1";
    public static int port = 8888;

    public static void main(String[] args) {
        start();
    }

    private static void start() {
        start(userid, userName, host, port);
    }

    private static void start(String userid, String userName, String host, int port) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ServerIdleHandler());
                        socketChannel.pipeline().addLast(PacketCodecHandler.getInstance());
                        socketChannel.pipeline().addLast(new ClientIdleHandler());
                        socketChannel.pipeline().addLast(new LoginHandler(userid, userName));
                        socketChannel.pipeline().addLast(LoginResponseHandler.getInstance());
                        socketChannel.pipeline().addLast(MessageResponseHandler.getInstance());
                    }
                });
        ChannelFuture future = bootstrap.connect(host, port).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    logger.info("connect to server success!");
                } else {
                    logger.info("failed to connect the server! ");
                    System.exit(0);
                }
            }
        });
    }

}
